import React, { useState, useEffect } from 'react';
import styles from '../css/questionDetails.module.css';
import leftImg from '../assets/left.png';
import hourseImg from '../assets/hourse3.png';
import loveImg from '../assets/love.png';
import defaultAvatar from '../assets/avatar.jpg';
import { useNavigate } from 'react-router-dom';
import { imgUrl } from '../config'; // 导入imgUrl
function QuestionsDetails() {
    // 安全获取 quesdata，并提供默认值
    const quesdata = JSON.parse(sessionStorage.getItem("quesdata")) || {
        content: '我的评论很多！',
        name: 'lv',
        create_time: '发布于2023-03-03',
        avatar: '',
        children: []
    };

    console.log(quesdata);
    const navigate = useNavigate();
    // 存储用户输入的内容
    const [inputContent, setInputContent] = useState('');

    // 存储评论列表，初始值从 sessionStorage 中获取，若没有则为 quesdata.children
    const [comments, setComments] = useState(() => {
        const storedComments = sessionStorage.getItem('comments');
        return storedComments ? JSON.parse(storedComments) : (quesdata.children || []);
    });

    // 控制提示弹窗的显示和隐藏
    const [showToast, setShowToast] = useState(false);

    // 返回到上一页
    const left = () => {
        window.history.back(-1);
    };

    // 跳转到首页
    const first = () => {
        navigate("/home");
    };

    // 图片错误处理
    const handleImageError = (e) => {
        e.target.src = defaultAvatar;
    };

    // 渲染回答列表
    const renderAnswers = () => {
        if (comments.length === 0) {
            return (
                <div className={styles['all-one']}>
                    <div className={styles.imgs}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <img src={defaultAvatar} alt="默认头像" onError={handleImageError} />
                            <span style={{ fontSize: '14px', color: '#424242', marginLeft: '5px' }}>暂无回答</span>
                        </div>
                    </div>
                </div>
            );
        }

        return comments.map((child, index) => (
            <div className={styles['all-one']} key={index}>
                <div className={styles.imgs}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img
                            src={child.avatar ? `${imgUrl}${child.avatar}` : defaultAvatar}
                            alt="用户头像"
                            onError={handleImageError}
                        />
                        <span style={{ fontSize: '14px', color: '#424242', marginLeft: '5px' }}>
                            {child.name || "lv"}
                        </span>
                    </div>
                    <div className={styles.image}>
                        <img src={loveImg} alt="点赞" />
                        <span>0</span>
                    </div>
                </div>
                <span style={{ display: 'block', marginTop: '10px', marginLeft: '10px' }}>
                    {child.content}
                </span>
            </div>
        ));
    };

    // 发表按钮点击事件处理函数
    const handlePost = () => {
        if (inputContent.trim() === '') {
            return;
        }

        // 创建新的评论对象
        const newComment = {
            name: "lv",
            avatar: '',
            content: inputContent
        };

        // 更新评论列表
        setComments([...comments, newComment]);
        // 存储更新后的评论列表到 sessionStorage
        sessionStorage.setItem('comments', JSON.stringify([...comments, newComment]));
        // 清空输入框
        setInputContent('');
        // 显示提示弹窗
        setShowToast(true);
        // 延迟一段时间后隐藏弹窗
        setTimeout(() => {
            setShowToast(false);
        }, 2000);
    };

    // 每次评论列表更新时，将其存储到 sessionStorage
    useEffect(() => {
        sessionStorage.setItem('comments', JSON.stringify(comments));
    }, [comments]);

    return (
        <div>
            {showToast && (
                <div style={{
                    position: 'fixed',
                    top: '30px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    backgroundColor: '#f0f0f0',
                    padding: '10px 20px',
                    textAlign: 'center',
                    zIndex: 1000,
                    borderRadius: '8px'
                }}>
                    发表成功
                </div>
            )}
            <div className={styles.top}>
                <div style={{ display: 'flex', alignItems: 'center', whiteSpace: 'nowrap', width: '50%', justifyContent: 'space-between' }}>
                    <div className={styles.left}>
                        <img src={leftImg} alt="返回" onClick={left} />
                        <div className={styles.line}></div>
                        <img id="hourse" src={hourseImg} alt="首页" onClick={first} />
                    </div>
                </div>
                <p>问答详情</p>
            </div>
            <div className={styles.big}>
                <div style={{ width: '92%', marginLeft: '4%', padding: '5px 0' }}>
                    <span style={{ fontSize: '14px', color: '#323232' }} id="maeny">
                        {quesdata.content}
                    </span>
                </div>
                <div className={styles.img}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img
                            id="head"
                            src={quesdata.avatar ? `${imgUrl}${quesdata.avatar}` : defaultAvatar}
                            alt="用户头像"
                            onError={handleImageError}
                        />
                        <span style={{ fontSize: '14px', color: '#424242', marginLeft: '5px' }} id="name">
                            {quesdata.name}
                        </span>
                    </div>
                    <span style={{ marginRight: '10px' }} id="time">
                        {quesdata.create_time}
                    </span>
                </div>
            </div>
            <div className={styles.all}>
                <b>全部回答（<span id="num">{comments.length}</span>）</b>
                <div className={styles.mom}>
                    {renderAnswers()}
                </div>
            </div>
            {/* 添加底部搜索框和发表按钮 */}
            <div className={styles.bottomContainer}>
                <input
                    type="text"
                    className={styles.searchInput}
                    placeholder="搜索"
                    value={inputContent}
                    onChange={(e) => setInputContent(e.target.value)}
                />
                <button className={styles.postButton} onClick={handlePost}>发表</button>
            </div>
        </div>
    );
}

export default QuestionsDetails;